package com.stjb.furns.filter;

import com.google.gson.Gson;
import com.stjb.furns.entity.Member;
import com.stjb.furns.utils.WebUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * @author situ
 * @version 1.0
 * @date 2025/5/30 2:37
 * @Description: 权限过滤 登录则放行 否则返回登陆页面
 */
public class AuthFilter implements Filter {

    private List<String> excludedUrls;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 获取配置的excludedUrls
        String strExcludedUrls = filterConfig.getInitParameter("escludedUrls");
        String[] split = strExcludedUrls.split(",");
        excludedUrls = Arrays.asList(split);

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String url = request.getServletPath();
        // System.out.println("请求的url = " + url);

        //判断是否要验证
        if (!excludedUrls.contains(url)){//需要验证
            Member member = (Member) request.getSession().getAttribute("member");
            if (null == member){

                //判断是不是ajax请求
                if (!WebUtils.isAjax(request)){
                    //用户未登录
                    request.getRequestDispatcher("/views/member/login.jsp").forward(request,servletResponse);
                }else {
                    //返回url
                    Gson gson = new Gson();
                    HashMap<String, Object> resultHashMap = new HashMap<>();
                    resultHashMap.put("url","views/member/login.jsp");
                    String resultGson= gson.toJson(resultHashMap);
                    servletResponse.getWriter().write(resultGson);
                }

                //返回
                return;
            }
        }
        //得到Session中的对象
        //继续访问
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }
}
